package com.firegod.course.service;

import com.firegod.commonutils.result.ResultCode;
import com.firegod.servicebase.dao.ChapterRepository;
import com.firegod.servicebase.dao.CourseRepository;
import com.firegod.servicebase.entity.Chapter;
import com.firegod.servicebase.entity.Course;
import com.firegod.servicebase.exceptionhandler.exception.GuliException;
import com.firegod.servicebase.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ChapterService extends BaseService<Chapter, Long, ChapterRepository> {

    @Autowired
    private CourseRepository courseRepository;

    public Map<String, Object> addChapter(String courseId, Integer sort, String title) {
        Course course = courseRepository.getCourseByCourseId(courseId);
        System.out.println("课程id为:" + courseId);
        if (course == null) {
            throw GuliException.from(ResultCode.COURSE_NOT_EXIST);
        }
        if (title == null || title.length() == 0) {
            throw GuliException.from(ResultCode.NO_TITLE);
        }
        Chapter chapter = new Chapter(sort, title);
        course.getChapterList().add(chapter);

        baseRepository.saveAndFlush(chapter);

        HashMap<String, Object> hashMap = new HashMap<>();
        var chapters = course.getChapterList();

        hashMap.put("chapterList", chapters.stream().map(Chapter::show));
        return hashMap;
    }

    public void deleteChapter(Long chapterId) {
        baseRepository.deleteById(chapterId);
    }
}
